package com.gzpi.hwgggh.controller;


import com.gzpi.hwgggh.entity.DWTP;
import com.gzpi.hwgggh.mapper.DWTPMapper;
import com.gzpi.hwgggh.sysenum.EnumErrorCode;
import com.gzpi.hwgggh.utils.FileResult;
import com.gzpi.hwgggh.utils.FileUtil;
import com.gzpi.hwgggh.utils.HwggConstants;
import com.gzpi.hwgggh.utils.Result;
import net.lingala.zip4j.core.ZipFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("DomXml")
@CrossOrigin
public class DomXml {

    @Autowired
    private DWTPMapper dwtpMapper;

    /**
     * 20210416 修改全景问题
     * 全景图框选：可选择填充或不填充
     * 全景换颜色  （blue>0x00BFFF）
     * @return
     */
    @RequestMapping("/updateTourXml")
    public Result updateTourXml(){
        try {
        List<DWTP> dwtps = dwtpMapper.selectDWTPList();
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File(HwggConstants.getPath()+"720全景/tour.xml"));//新文件
        Element documentRoot = document.getRootElement();//新文件的根节点
        List<Element> documentNodes = documentRoot.elements("style");//新文件 获取所有的style节点
        for (DWTP dwtp : dwtps) {
                Document doc = reader.read(new File(HwggConstants.getPanFu() + dwtp.getGHQJT() + "/tour.xml"));//要更新的文件
                //获取文档根节点
                Element docRoot = doc.getRootElement();//要更新的文件的根节点
                List<Element> docNodes = docRoot.elements("style");//更新文件 获取所有的style节点
                for (int i = 2; i < docNodes.size(); i++) {//删除原来的节点
                    System.out.println(docNodes.get(i).asXML());
                    docRoot.remove(docNodes.get(i));
                }
                int index = 12;
                List<Element> elements = docRoot.elements();
                for(int i = 0; i < elements.size(); i++){
                    Element element = elements.get(i);
                    if (element.getName().equals("action")){
                        Attribute attribute = element.attribute("name");
                        if ("outputsnum".equals(attribute.getValue())){
                            index = i;
                            break;
                        }
                    }
                }

                for (int i = 2; i < documentNodes.size(); i++) { //添加新的节点
                    index+=1;
                    elements.add(index,(org.dom4j.Element) documentNodes.get(i).clone());
                }

                List<org.dom4j.Element> hotspots = docRoot.elements("hotspot");
                for (Element hotspot : hotspots) {
                    Attribute attr = hotspot.attribute("style");
                    if ("polygon_blue".equals(attr.getValue())){
                        List<Attribute> attributes = hotspot.attributes();
                        for (Attribute attribute : attributes) {
                            if ("bordercolor".equals(attribute.getName())) {
                                attribute.setValue("0x00BFFF");
                                hotspot.setAttributes(attributes);
                                break;
                            }
                        }
                    }
                }
                OutputFormat format = OutputFormat.createPrettyPrint();
                format.setEncoding("UTF-8");
                XMLWriter writer = new XMLWriter(new FileWriter(HwggConstants.getPath() + dwtp.getGHQJT() + "/tour.xml"),format);
                writer.write(doc);
                writer.close();
        }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.createSuccess("修改成功");
    }

    /**
     * 文件转移
     * @param request
     * @return
     */
    @RequestMapping("/replaceFile")
    public Result replaceFile(HttpServletRequest request){
        List<DWTP> dwtps = dwtpMapper.selectDWTPList();
        for (DWTP dwtp : dwtps) {
            try
            {
                FileInputStream fis = new FileInputStream(HwggConstants.getPath()+"720全景/note_tool_plugin.xml");//创建输入流对象
                FileOutputStream fos = new FileOutputStream(HwggConstants.getPath()+dwtp.getGHQJT()+"/note_tool/note_tool_plugin.xml"); //创建输出流对象
                byte datas[] = new byte[1024*8];//创建搬运工具
                int len = 0;//创建长度
                while((len = fis.read(datas))!=-1)//循环读取数据
                {
                    fos.write(datas,0,len);
                }
                fis.close();//释放资源
                fos.close();//释放资源
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return Result.createSuccess("成功");
    }

    /**
     * 修改新全景
     * @return
     */
    @RequestMapping("updateNewQj")
    public Result updateNewQj(){
        try {

            SAXReader reader = new SAXReader();

            String path = HwggConstants.getPath()+"/720全景/测试";

            Document document = reader.read(new File(path+"/tour.xml"));//模板文件
            Element documentRootElement = document.getRootElement();//模板文件根节点
            List<Element> documentElements = documentRootElement.elements();//模板文件所有节点
            List<Element> documentInclude = documentRootElement.elements("include");//模板文件所有include节点

            List<Element> documentList = new ArrayList<>(); //保存要新增的节点
            boolean isScene = false;//判断是否出现scene节点
            for (int i = 0 ; i < documentElements.size() ; i++) {
                if (!isScene) {
                    if ("scene".equals(documentElements.get(i).getName())) {
                        isScene = true;
                    }
                }else{
                    documentList.add(documentElements.get(i));
                }
            }

            File  dir= new File(path);
            String[] children = dir.list();//所有目录
            for (int i=0; i<children.length; i++) {//遍历所有目录
                File qjFile = new File(path+"/"+children[i]);
                if (qjFile.isDirectory()){
                    isScene = false;

                    ZipFile zipFile = new ZipFile(new File(path+"/全景.zip"));//
                    zipFile.setFileNameCharset("UTF-8");//字符集
                    zipFile.extractAll(path+"/"+children[i]+"/vtour");//



                    Document doc = reader.read(new File(path+"/"+children[i]+"/vtour/tour.xml"));//修改文件

                    Element docRootElement = doc.getRootElement();//修改文件根节点

                    List<Element> docElements = docRootElement.elements();//修改文件所有节点

                    for (int j = 1 ; j < documentInclude.size() ; j++){ //添加include节点
                        docElements.add(j, (Element) documentInclude.get(j).clone());
                    }

                    Element docSkin_settings = docRootElement.element("skin_settings");//修改文件skin_settings节点
                    List<Attribute> attributes = docSkin_settings.attributes();//所有属性
                    for (Attribute attribute : attributes) {
                        if ("maps".equals(attribute.getName())) {
                            attribute.setValue("true");
                        } else if ("controlbar_height".equals(attribute.getName())) {
                            attribute.setValue("0");
                        } else if ("controlbar_offset".equals(attribute.getName())) {
                            attribute.setValue("-20");
                        }
                    }

                    Element documentAction = documentRootElement.elements("action").get(0);//模板文件第一个action节点
                    Element docAction = docRootElement.elements("action").get(0);//修改文件第一个action节点
                    String documentActionText = documentAction.getText();
                    docAction.setText(documentActionText);

                    Element docScene = docRootElement.element("scene");//修改文件scene节点
                    Element docSceneImage = docScene.element("image");
                    docSceneImage.addAttribute("mapscale","100");

                    for (Element element : documentList) {
                        docRootElement.add((Element) element.clone());
                    }

                    OutputFormat format = OutputFormat.createPrettyPrint();
                    format.setEncoding("UTF-8");
                    XMLWriter writer = new XMLWriter(new FileWriter(path+"/"+children[i]+"/vtour/tour.xml"),format);
                    writer.write(doc);
                    writer.close();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.createSuccess("修改成功");
    }

    /**
     * 修改Mapscale值
     * @param dwxid
     * @param value
     * @return
     */
    @RequestMapping("/updateMapscale")
    public Result updateMapscale(String dwxid,String value){
        try {
            if (StringUtils.isBlank(dwxid) || StringUtils.isBlank(value)){
                return Result.createError(EnumErrorCode.ERROR_MESSAGE.toString("参数不能为空!"));
            }
            SAXReader reader = new SAXReader();
            DWTP dwtp = dwtpMapper.selectDWTPbyMap(new HashMap(){{put("FID",dwxid);}});
            if (StringUtils.isNotBlank(dwtp.getXZQJT()))updateQjMapscale(value,HwggConstants.getPanFu()+dwtp.getXZQJT()+"/tour.xml",reader);
            if (StringUtils.isNotBlank(dwtp.getGHQJT()))updateQjMapscale(value,HwggConstants.getPanFu()+dwtp.getGHQJT()+"/tour.xml",reader);
            if (StringUtils.isNotBlank(dwtp.getCCQJT()))updateQjMapscale(value,HwggConstants.getPanFu()+dwtp.getCCQJT()+"/tour.xml",reader);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.createError("修改失败");
        }
        return Result.createSuccess("修改成功");
    }

    public void updateQjMapscale(String value,String path,SAXReader reader) throws Exception{
        Document document = reader.read(new File(path));//模板文件
        Element documentRootElement = document.getRootElement();//根节点
        Element scene = documentRootElement.element("scene");
        Element image = scene.element("image");
        List<Attribute> attributes = image.attributes();
        for (Attribute attribute : attributes) {
            if (attribute.getName().equals("mapscale")){
                attribute.setValue(value);
            }
        }

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writer = new XMLWriter(new FileWriter(path),format);
        writer.write(document);
        writer.close();
    }

    /**
     * 生成xml方法
     */
    @RequestMapping(value = "/createXml.do",method = RequestMethod.POST)
    public void createXml(String str,String path){
        System.out.println(path);
        //  path = path.replace("HWGGP/","");
        randomAccessWrite(path,str);
    }
    public void randomAccessWrite(String filePath, String content) {
        content = content.replace("null","");
        File fileName = new File(filePath+"/tour.xml");
        content += "</krpano>";
        RandomAccessFile randomFile = null;
        try {
            // 创建解析器工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            org.w3c.dom.Document document = db.parse("file:///"+filePath+"/tour.xml");
            //得到所有p1
            NodeList list = document.getElementsByTagName("krpano");
            Node p1=list.item(0);
            NodeList list1 = document.getElementsByTagName("hotspot");
            for(int i =list1.getLength()-1;i>-1;i--){
                p1.removeChild(list1.item(i));
            }
            // 创建TransformerFactory对象
            TransformerFactory tff = TransformerFactory.newInstance();
            // 创建 Transformer对象
            Transformer tf = tff.newTransformer();
            // 输出内容是否使用换行
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            // 创建xml文件并写入内容
            tf.transform(new DOMSource(document), new StreamResult(new File(filePath+"/tour.xml")));
            // 打开一个随机访问文件流，按读写方式
            randomFile = new RandomAccessFile(fileName, "rw");
            // 文件长度，字节数
            long fileLength = randomFile.length();
            // 将写文件指针移到文件尾。
            // byte[] buffer = new byte[1024];
            randomFile.seek(fileLength-11);
            randomFile.write(content.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (randomFile != null) {
                try {
                    randomFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
